package lumis.service.report.control;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

import lumis.doui.control.Control;
import lumis.doui.source.Source;
import lumis.doui.source.SourceFactory;
import lumis.portal.PortalException;
import lumis.portal.manager.ManagerFactoryInternal;
import lumis.portal.report.Report;
import lumis.portal.report.ReportType;
import lumis.util.IResource;
import lumis.util.XmlUtil;

/**
 * Base control for report parameter controls.
 *
 * @version $Revision: 12710 $ $Date: 2011-03-18 17:00:16 -0300 (Fri, 18 Mar 2011) $
 * @since 4.1.0
 */
public abstract class BaseParametersControl extends Control
{
	protected ReportType reportType = null;
	
	public void buildSubControls() throws PortalException
	{
		super.buildSubControls();
		
		// get the report type
		String reportTypeId = douiContext.getRequest().getParameter("reportTypeId");
		if (reportTypeId == null)
		{
			String id = douiContext.getRequest().getParameter("id");
			if (id != null)
			{
				Report report = ManagerFactoryInternal.getReportManager().getReport(id);
				reportType = report.getReportType();
			}
		}
		else
		{
			reportType = ManagerFactoryInternal.getReportManager().getReportType(reportTypeId);
		}
		
		if (reportType != null)
		{
			StringBuilder subControls = new StringBuilder();
			
			// add new source node
			Node sourceNode = getSourceNode(reportType);
			
			Node sourcesNode = XmlUtil.selectSingleNode("/douiDefinition/service/sources", controlDefinitionNode);
			Node importedNode = sourcesNode.getOwnerDocument().importNode(sourceNode, true);
			Node newSourceNode = sourcesNode.appendChild(importedNode);
			
			Source newSource = SourceFactory.createSource(newSourceNode, douiContext.getSourceContainer().getSourceContext());
			douiContext.getSourceContainer().addSource(newSource);
			
			subControls.append(XmlUtil.getXmlString((Element)getControlsNode(reportType)));
	
			appendSubControls(subControls.toString());
		}
	}
	
	@Override
	public IResource getControlResource() throws PortalException
	{
		IResource controlResource = super.getControlResource();
		
		if(reportType != null)
			controlResource.addResourcePath(reportType.getStringsUrlPrefix());
		
		return controlResource;
	}

	protected abstract Node getSourceNode(ReportType reportTypeConfig) throws PortalException;

	protected abstract Node getControlsNode(ReportType reportTypeConfig) throws PortalException;
}
